package com.shine.common.service;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;

import com.shine.common.Constants;
import com.shine.common.repository.hibernate.HibernateDao;
import com.shine.common.web.model.Page;

public abstract class BaseServiceImpl<M extends java.io.Serializable, PK extends java.io.Serializable> implements BaseService<M, PK> {

	@Autowired
	protected HibernateDao<M, Serializable> dao;

	private Class<M> entityClass;

	@SuppressWarnings("unchecked")
	@PostConstruct
	public void init() {
		// 1、通过反射获取注解“M”（即模型对象）的类类型
		this.entityClass = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public HibernateDao<M, Serializable> getDao() {
		return dao;
	}

	public void setDao(HibernateDao<M, Serializable> dao) {
		this.dao = dao;
	}

	@Override
	public M save(M entity) {
		getDao().save(entity);
		return entity;
	}

	@Override
	public void saveOrUpdate(M entity) {
		getDao().saveOrUpdate(entity);
	}

	@Override
	public void update(M entity) {
		getDao().update(entity);
	}

	@Override
	public void delete(PK id) {
		getDao().delete(entityClass, id) ;
	}
	
	@Override
	public void deleteMoreforString(String ids) {
		if(null != ids && ids.length() > 0) {
			String[] split = ids.split(",") ;
			for (String id : split) {
				getDao().delete(entityClass, id) ;
			}
		}
	}
	
	@Override
	public void deleteMoreforInt(String ids) {
		if(null != ids && ids.length() > 0) {
			String[] split = ids.split(",") ;
			for (String id : split) {
				getDao().delete(entityClass, Integer.parseInt(id)) ;
			}
		}
	}

	@Override
	public M get(PK id) {
		return getDao().getEntity(entityClass, id) ;
	}

	@Override
	public int countAll() {
		Number total = (Number) getDao().countAll(entityClass) ;
		return total.intValue() ;
	}

	@Override
	public List<M> listAll() {
		return getDao().listAll(entityClass) ;
	}

	@Override
	public Page<M> listAll(int currentPage) {
		return getDao().listAll(entityClass, currentPage, Constants.PAGE_NUMBER);
	}

	@Override
	public Page<M> listAll(int currentPage, int pageSize) {
		return getDao().listAll(entityClass, currentPage, pageSize);
	}
}
